<template>
  <div class="account-box">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="手机号" prop="username" class="margin-top10">
        <el-input v-model="ruleForm.username" clearable />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="ruleForm.password"
          clearable
          show-password
          @keyup.enter.native="submitForm(ruleFormRef)"
        />
      </el-form-item>
      <el-form-item class="remember-me">
        <el-checkbox v-model="isRememberMe">记住我</el-checkbox>
      </el-form-item>
      <div class="btns">
        <el-button type="primary" @click="submitForm(ruleFormRef)" round>
          登 录
        </el-button>
        <el-button type="success" @click="goRegister" round>
          注 册
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)" round
          >重 置</el-button
        >
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue';
import { useRouter } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
// class
import { RuleForm, LoginForm } from "@/types/Login/loginClass";
// 消息弹出框
import { showMessageBox, showNotification } from "@/utils/alertMsg";
// 缓存
import storageFn from "@/utils/storage";
// api
import loginApi from "@/request/api/login";
// store
import useLoginStore from "@/store/login";

const router = useRouter();
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>(new LoginForm("", ""));
// 是否记住账号和密码
const isRememberMe = ref(false);
const loginStore = useLoginStore();

const rules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: "请输入用户名或者账号", trigger: "blur" },
    { min: 3, max: 15, message: "长度在3-15个字符之间", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, message: "密码长度至少5个字符", trigger: "blur" },
  ],
});

const REMEMBER_KEY = "reUser";
// "记住我"回调
const rememberMeCallBack = () => {
  if (!isRememberMe.value) {
    // 不记住
    return storageFn.removeStorage("local", REMEMBER_KEY);
  }
  storageFn.setStorage("local", REMEMBER_KEY, ruleForm);
};

watch(isRememberMe, (val) => {
  // 调用《记住我》方法
  rememberMeCallBack();
});

onMounted(() => {
  // 记住我
  const reUser = storageFn.getStorage("local", REMEMBER_KEY);
  if (reUser) {
    ruleForm.username = reUser.username;
    ruleForm.password = reUser.password;
    isRememberMe.value = true;
  }
});

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      /* 老方法==================================== 
        const params = {
          phone: ruleForm.username,
          password: ruleForm.password
        }
        loginApi.loginByPassword(params).then((res: any) => {
          // console.log(res);
          if(res.code == 200) {
            showMessageBox("success", res.msg)
            loginStore.setToken(res.data.token);
            // loginStore.getAndSetUserInfo()
            // 跳转到首页
            setTimeout(() => {
              router.push("/home");
            }, 100)
          } else if (res.code == 201) {
            showMessageBox("error", res.msg)
          }
        });
      */

      // 新接口
      const params = {
        phone: ruleForm.username,
        password: ruleForm.password,
        imageBase: ''
      }
      loginApi.useLogin(params).then((res: any) => {
        if(res.code == 200) {
            showMessageBox("success", res.msg)
            loginStore.setToken(res.data.token);
            // 跳转到首页
            setTimeout(() => {
              router.replace("/home");
            }, 100)
          } else {
            showMessageBox("error", res.msg)
          }
      });
    } else {
      // ruleForm.resetFields();
      showNotification("error", "提示", "验证未通过");
    }
  });
};

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  isRememberMe.value = false;
};

// 去登录页面
const goRegister = (): void => {
  router.push('/register')
}
</script>

<style scoped lang="scss">
.account-box {
  .el-form {
    border-top: 1px solid #000;
    padding-right: 30px;
    // .margin-top10 {
    //   margin: 1vw 0;
    // }
    // .remember-me {
    //   margin-top: 0.8vw;
    // }
    .el-form-item {
      margin: 1vw 0;
    }
  }
}

.btns {
  // border: 1px solid red;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 1vw;
  .el-button {
    width: 5.5vw;
  }
}
</style>
